//
//  SYS_AmendPasswordVC.m
//  System_App
//
//  Created by 伟徐 on 2017/11/28.
//  Copyright © 2017年 czy001. All rights reserved.
//

#import "SYS_AmendPasswordVC.h"
#import "SYS_MinePasswordCell.h"
#import "ApplyViewController.h"


@interface SYS_AmendPasswordVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, strong) SYS_PublicPopView *popAlertView;
//@property (nonatomic, strong) WHC_KBMConfiguration * configuration;
@property (nonatomic, strong) UITextField *currentTF;
@property (nonatomic, strong) UITableView*tableView;
@property (nonatomic, copy) NSString *oldPSW;
@property (nonatomic, copy) NSString *freshPSW;
@property (nonatomic, copy) NSString *confirmPSW;
@property (nonatomic, copy) NSArray *logoArray;

@end

@implementation SYS_AmendPasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    [self initTableView];
    [self setNavigationBar];
}

#pragma mark -- setter and getter
- (void)setNavigationBar{
    self.title = @"修改登录密码";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"SYS_Public_back" highImage:nil title:nil target:self action:@selector(amendPasswordVCBack)];
    self.view.backgroundColor =RGBACOLOR(240, 240, 240, 1);
}

-(void)initTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH,SCREENHEIGHT-NavBarHeight) style:UITableViewStyleGrouped];
    _tableView.delegate =self;
    _tableView.dataSource =self;
    _tableView.backgroundColor =RGBACOLOR(240, 240, 240, 1);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview: _tableView];
    [_tableView registerClass:[SYS_MinePasswordCell class] forCellReuseIdentifier:@"SYS_MinePasswordCell"];
    
    UIButton *logoutBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    logoutBtn.frame =CGRectMake(20, 65*self.logoArray.count+15, SCREENWIDTH-40, 48);
    logoutBtn.backgroundColor = MainColor;
    logoutBtn.layer.cornerRadius = 24;
    logoutBtn.layer.masksToBounds = YES;
    logoutBtn.titleLabel.font =[UIFont systemFontOfSize:18];
    [logoutBtn setTitle:@"确认修改" forState:UIControlStateNormal];
    [logoutBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [logoutBtn addTarget:self action:@selector(gotoAmendPassword) forControlEvents:UIControlEventTouchUpInside];
    [_tableView addSubview:logoutBtn];
    
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    tap.numberOfTapsRequired=1;
    tap.delegate=self;
    [self.view addGestureRecognizer:tap];
}

#pragma mark -- touch and event
- (void)amendPasswordVCBack{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)gotoAmendPassword{
    [self hideKeyboard];
    if(_oldPSW.length == 0){
        [MBProgressHUD showError:@"原密码输入不能为空" toView:self.view];
        return;
    }
    
    if(_freshPSW.length == 0){
        [MBProgressHUD showError:@"新密码输入不能为空" toView:self.view];
        return;
    }
    
    if(_freshPSW.length < 6){
        [MBProgressHUD showError:@"新密码输入不能少于六位" toView:self.view];
        return;
    }

    if(_confirmPSW.length == 0){
         [MBProgressHUD showError:@"确认密码输入不能为空" toView:self.view];
        return;
    }
    
    if (![_freshPSW isEqualToString:_confirmPSW]) {
        [MBProgressHUD showError:@"两次输入密码不一致" toView:self.view];
        return;
        
    }
    NSString *session = [SYS_LoginModel instance].sessionInfo.session;
    
    UICKeyChainStore *keychainStore = [UICKeyChainStore keyChainStore];
    NSString *pid = [keychainStore stringForKey:@"pid"];
    
    NSDictionary *params = @{
                             @"session":session,
                             @"pid":pid,
                             @"oldPassword":_oldPSW,
                             @"newPassword":_freshPSW
                             };
    NSString *url=[NSString stringWithFormat:@"%@/adm/sysapp/updatePasswd",SERVICE_IP];
    [self showHudInView:self.view hint:@"正在加载..."];
    [NetRequestClass NetRequestGETWithRequestURL:url WithParameter:params WithReturnValeuBlock:^(id returnValue) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSString *flag=returnValue[@"flag"];
        if ([flag isEqualToString:@"true"]) {
            [self initPopAlertView];
            [self performSelector:@selector(gotoLogin) withObject:self afterDelay:1.5];
            
        }else{
            [MBProgressHUD showSuccess:returnValue[@"exp"] toView:self.view];
        }
    } WithErrorCodeBlock:^(id errorCode) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } WithFailureBlock:^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showSuccess:@"网络请求错误!" toView:self.view];
    }];
    
}

-(void)initPopAlertView{
    _popAlertView =[[SYS_PublicPopView alloc] initwithtitleText:@"修改成功" withMessage:@"" andcancelbtn:nil andotherbtn:nil withIconStr:@"Mine_Lock" andCancelBtnImageNameStr:@"" andSureBtnImageNameStr:@""];
    [_popAlertView show];
}

-(void)gotoLogin{
    [_popAlertView dismmis1];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [[ApplyViewController shareController] clear];
    
    //删除归档文件
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    if ([defaultManager isDeletableFileAtPath:LoginFilePath]) {
        [defaultManager removeItemAtPath:LoginFilePath error:nil];
    }
    //删除存储信息
    [SYS_LoginModel instance].sessionInfo=nil;
    [SYS_LoginModel instance].user=nil;
    [SYS_LoginModel instance].admin=nil;
    
    if ([defaultManager isDeletableFileAtPath:PhonePwdFilePath]) {
        [defaultManager removeItemAtPath:PhonePwdFilePath error:nil];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO userInfo:@{@"isLogin":@"no"}];
}

- (void)hideKeyboard{
    [_currentTF resignFirstResponder];
}

#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(nonnull UITouch *)touch{
    
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"] || [NSStringFromClass([touch.view class]) isEqualToString:@"UIImageView"]) {
        return NO;
    }
    return YES;
}

#pragma mark UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    _currentTF=textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    switch (textField.tag) {
        case 1000:
            _oldPSW = textField.text;
            break;
            
        case 1001:
            _freshPSW = textField.text;
            break;
            
        case 1002:
            _confirmPSW= textField.text;
            break;
            
        default:
            break;
    }
    
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self hideKeyboard];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    if (textField.tag == 1000||textField.tag==1001||textField.tag==1002)  //判断是否时我们想要限定的那个输入框
        
    {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789._qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        
        if ([toBeString length] > 20) { //如果输入框内容大于20则弹出警告
            
            
            textField.text = [toBeString substringToIndex:20];
            
            return NO;
            
        }else{
            return [string isEqualToString:filtered];
        }

    }
    return YES;
}

#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.logoArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    SYS_MinePasswordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SYS_MinePasswordCell" forIndexPath:indexPath];
    cell.selectionStyle =  UITableViewCellSelectionStyleNone;
    cell.logoImg.image= [UIImage imageNamed:self.logoArray[indexPath.row]];
    cell.pswTextField.tag =indexPath.row + 1000;
    switch (indexPath.row) {
        case 0:{
            cell.pswTextField.placeholder =@"原密码";
        }
            break;
        case 1:{
            cell.pswTextField.placeholder =@"新密码";
        }
            break;
        case 2:{
            cell.pswTextField.placeholder =@"请确认新密码";
        }
            break;
        default:
            break;
    }
    cell.pswTextField.delegate =self;
    return cell;
}


#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 65;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

#pragma mark - 懒加载控件
-(NSArray *)logoArray{
    if(!_logoArray){
        _logoArray = [NSArray arrayWithObjects:@"Mine_OldPSW",@"Mine_AmendPSW",@"Mine_SurePSW",nil];
    }
    return _logoArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
